package com.ruoyi.system.service.impl.fxImpl;

import com.ruoyi.common.enums.GeneralStatus;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.fx.FxReceiveAddress;
import com.ruoyi.system.domain.fx.FxStore;
import com.ruoyi.system.mapper.fx.FxReceiveAddressMapper;
import com.ruoyi.system.mapper.fx.FxStoreMapper;
import com.ruoyi.system.service.fx.IFxReceiveAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

import static com.ruoyi.system.service.impl.fxImpl.FxStoreServiceImpl.calculateDistance;


/**
 * 收货地址维护Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@Service
public class FxReceiveAddressServiceImpl implements IFxReceiveAddressService {
    @Autowired
    private FxReceiveAddressMapper fxReceiveAddressMapper;
    @Autowired
    private FxStoreMapper fxStoreMapper;

    /**
     * 查询收货地址维护
     *
     * @param id 收货地址维护主键
     * @return 收货地址维护
     */
    @Override
    public FxReceiveAddress selectFxReceiveAddressById(Long id) {
        return fxReceiveAddressMapper.selectFxReceiveAddressById(id);
    }

    /**
     * 查询收货地址列表并排序
     *
     * @param fxReceiveAddress
     * @return
     */
    @Override
    public FxReceiveAddress selectRecentlyOrDefault(FxReceiveAddress fxReceiveAddress) {
        // 获取当前登录人id
        Long userId = SecurityUtils.getUserId();
        fxReceiveAddress.setUserId(userId);
        // 查询当前登录人全部收货地址
        Collection<FxReceiveAddress> receiveAddress = getAllAddressList(fxReceiveAddress);
        // 判断地址是否为空
        if (!CollectionUtils.isEmpty(receiveAddress)) {
            // 循环地址
            for (FxReceiveAddress address : receiveAddress) {
                // 获取地址是否可选
                if (address.getChoice()) {
                    // 有默认地址返回默认地址
                    if (Objects.equals(address.getIsDefault(), GeneralStatus.是.getCode())) {
                        return address;
                    }
                }
            }
            return receiveAddress.iterator().next();
        }
        return null;
    }

    /**
     * 查询地址
     *
     * @param fxReceiveAddress
     * @return
     */
    @Override
    public List<FxReceiveAddress> selectAddressList(FxReceiveAddress fxReceiveAddress) {
        // 传入当前登录人 id
        fxReceiveAddress.setUserId(SecurityUtils.getUserId());
        // 调取距离排序
        Collection<FxReceiveAddress> allAddressList = getAllAddressList(fxReceiveAddress);
        if(CollectionUtils.isEmpty(allAddressList)){
            return new ArrayList<>();
        }
        return new ArrayList<>(allAddressList); // 赋值 collection 是所有集合的父接口
    }

    public Collection<FxReceiveAddress> getAllAddressList(FxReceiveAddress fxReceiveAddress) {
        // 当前用户全部地址
        Collection<FxReceiveAddress> receiveAddress = fxReceiveAddressMapper.selectFxReceiveAddressList(fxReceiveAddress);
        if (receiveAddress.size() == 0)
            return null;
        // 判断 是否传入店铺id
        if (fxReceiveAddress.getId() == null) {
            // 未传入 直接输出全部地址
            return receiveAddress;
        }
        // 获取门店地址 下单传入门店id
        FxStore store = fxStoreMapper.selectFxStoreById(fxReceiveAddress.getId());
        String latitude = store.getLatitude(); // 纬度
        String longitude = store.getLongitude(); // 经度
        // 计算配送范围（m）
        String deliveryScope = new BigDecimal(5)
                .multiply(new BigDecimal("1000"))
                .setScale(2, RoundingMode.HALF_UP).toString();
        double scope = Double.parseDouble(deliveryScope); // 转为double

        // 收货地址按距离排序，由近至远
        Map<Double, FxReceiveAddress> treeMap = new TreeMap<>();
        // 循环全部地址 计算距离并插入
        receiveAddress.forEach(address -> {
            // 计算距离
            double distance = calculateDistance(
                    Double.parseDouble(latitude), // 当前门店纬度
                    Double.parseDouble(longitude), // 当前门店经度
                    Double.parseDouble(address.getLatitude()), // 循环地址纬度
                    Double.parseDouble(address.getLongitude())); // 循环地址经度
            address.setChoice(true); // 默认选中
            // 若当前距离存在 距离加0.01m
            if (treeMap.containsKey(distance))
                distance += 0.01;
            if (distance > scope) // 距离大于配送距离不可选中
                address.setChoice(false);
            treeMap.put(distance, address);// 存入map treeMap

            DecimalFormat decimalFormat = new DecimalFormat("#.##"); // 设置保留一位小数的格式
            String formattedDistance = decimalFormat.format((distance / 1000)); // 对double进行计算并格式化输出结果
            address.setDistance(formattedDistance);
        });
        receiveAddress = treeMap.values(); // 输出map的全部 value
        return receiveAddress;
    }

    /**
     * 查询收货地址维护列表
     *
     * @param fxReceiveAddress 收货地址维护
     * @return 收货地址维护
     */
    @Override
    public List<FxReceiveAddress> selectFxReceiveAddressList(FxReceiveAddress fxReceiveAddress) {
        return fxReceiveAddressMapper.selectFxReceiveAddressList(fxReceiveAddress);
    }

    /**
     * 新增收货地址维护
     *
     * @param fxReceiveAddress 收货地址维护
     * @return 结果
     */
    @Override
    public int insertFxReceiveAddress(FxReceiveAddress fxReceiveAddress) {
        fxReceiveAddress.setCreateDate(DateUtils.getNowDate());
        Long userId = fxReceiveAddress.getUserId();
        if (userId == null)
            userId = SecurityUtils.getUserId();
        fxReceiveAddress.setUserId(userId);
        if (fxReceiveAddress.getIsDefault() != null && Objects.equals(fxReceiveAddress.getIsDefault(), GeneralStatus.是.getCode())) {
            FxReceiveAddress address = new FxReceiveAddress();
            address.setUserId(userId);
            address.setIsDefault(GeneralStatus.否.getCode());
            fxReceiveAddressMapper.updateDefault(address);
        }
        return fxReceiveAddressMapper.insertFxReceiveAddress(fxReceiveAddress);
    }

    /**
     * 修改收货地址维护
     *
     * @param fxReceiveAddress 收货地址维护
     * @return 结果
     */
    @Override
    public int updateFxReceiveAddress(FxReceiveAddress fxReceiveAddress) {
        Long userId = fxReceiveAddress.getUserId();
        if (userId == null)
            userId = SecurityUtils.getUserId();
        fxReceiveAddress.setUserId(userId);
        if (fxReceiveAddress.getIsDefault() != null && Objects.equals(fxReceiveAddress.getIsDefault(), GeneralStatus.是.getCode())) {
            FxReceiveAddress address = new FxReceiveAddress();
            address.setUserId(userId);
            address.setIsDefault(GeneralStatus.否.getCode());
            fxReceiveAddressMapper.updateDefault(address);
        }
        return fxReceiveAddressMapper.updateFxReceiveAddress(fxReceiveAddress);
    }

    /**
     * 新增与修改
     * @param fxReceiveAddress 收货地址
     * @return
     */
    public int save(FxReceiveAddress fxReceiveAddress){
        Long id = fxReceiveAddress.getId();
        Long userId = fxReceiveAddress.getUserId();
        if (userId == null)
            userId = SecurityUtils.getUserId();
        fxReceiveAddress.setUserId(userId);
        if (fxReceiveAddress.getIsDefault() != null && Objects.equals(fxReceiveAddress.getIsDefault(), GeneralStatus.是.getCode())) {
            FxReceiveAddress address = new FxReceiveAddress();
            address.setUserId(userId);
            address.setIsDefault(GeneralStatus.否.getCode());
            fxReceiveAddressMapper.updateDefault(address);
        }
        // 校验手机号
        String regex = "^1[3-9]\\d{9}$";
        boolean isNum = fxReceiveAddress.getPhoneNumber().matches(regex);
        if (!isNum) {
            throw new GlobalException("请输入正确的手机号");
        }
        // 新增
        if (id == null) {
            fxReceiveAddress.setCreateDate(DateUtils.getNowDate());
            return fxReceiveAddressMapper.insertFxReceiveAddress(fxReceiveAddress);
        }else {
            return fxReceiveAddressMapper.updateFxReceiveAddress(fxReceiveAddress);
        }
    }

    /**
     * 批量删除收货地址维护
     *
     * @param ids 需要删除的收货地址维护主键
     * @return 结果
     */
    @Override
    public int deleteFxReceiveAddressByIds(Long[] ids) {
        return fxReceiveAddressMapper.deleteFxReceiveAddressByIds(ids);
    }

    /**
     * 删除收货地址维护信息
     *
     * @param id 收货地址维护主键
     * @return 结果
     */
    @Override
    public int deleteFxReceiveAddressById(Long id) {
        return fxReceiveAddressMapper.deleteFxReceiveAddressById(id);
    }
}
